package edu.gatech.gro.model.parser;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import edu.gatech.gro.model.AbstractObject;
import edu.gatech.gro.model.ObjectResponse;

public class JsonHandler {

	private static final String TAG = "JSON_HANDLER";

	protected JSONObject json;
	private ObjectResponse response;

	public final void parse(String jsonString) {
		response = new ObjectResponse();
		try {
			Log.d(TAG, jsonString);
			json = new JSONObject(jsonString);
			response.setSuccess(json.getBoolean("success"));
			if (response.isSuccessful()) {
				if (json.has("totalCount")) {
					response.setTotalCount(json.getInt("totalCount"));
				}
				if (json.optJSONArray("data") != null) {
					parseDataArray();
				} else {
					parseData();
				}
			} else {
				parseError();
			}
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
	}

	public ObjectResponse getResponse() {
		return response;
	}

	private final void parseError() {
		if (json.has("errors")) {
			List<String> errors = new ArrayList<String>();
			try {
				JSONArray array = json.getJSONArray("errors");
				for (int i = 0; i < array.length(); i++) {
					errors.add(array.getString(i));
				}
			} catch (JSONException e) {
				Log.e(TAG, e.getMessage());
			}
			response.setErrors(errors);
		}
	}

	protected void parseDataArray() {

	}

	protected void parseData() {

	}

	protected static void parseAbstractObject(AbstractObject ao, JSONObject obj) throws JSONException {
		if (ao != null) {
			if (obj.has("id")) {
				ao.setId(obj.getInt("id"));
			}
			if (obj.has("creationTime")) {
				ao.setCreationTime(obj.getInt("creationTime"));
			}
			if (obj.has("lastUpdateTime")) {
				ao.setLastUpdateTime(obj.getInt("lastUpdateTime"));
			}
			if (obj.has("deleteFlag")) {
				ao.setDeleteFlag(obj.getBoolean("deleteFlag"));
			}
		}
	}
}
